package com.zhiqingchun.web.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.zhiqingchun.pojo.Usr;

@Controller
@RequestMapping("/qqLogin.html")
public class QQLoginController {
	
	@RequestMapping(method = RequestMethod.GET)
	public String qqLogin(ModelMap modelMap,HttpServletRequest request, HttpServletResponse response) {
		try {
			System.out.println(request.getParameter("code"));
			AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
			String accessToken = null,
					openID = null;
			long tokenExpireIn = 0l;
			if (accessTokenObj.getAccessToken().equals("")) {
				try {
					throw new Exception("没有获取到Authorization Code");
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				accessToken = accessTokenObj.getAccessToken();
				tokenExpireIn = accessTokenObj.getExpireIn();
				OpenID openIDObj = new OpenID(accessToken);
				openID = openIDObj.getUserOpenID();
				request.getSession().setAttribute("openID", openID);
				UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
				UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
				request.getSession().setAttribute("qqUserInfo", userInfoBean);
				request.getSession().setAttribute("user", new Usr(userInfoBean.getLevel(), openID));
			}
		} catch (QQConnectException e) {
			e.printStackTrace();
		}
		return "redirect:default.html";
	}

}
